<template>
    <div>
        <el-card>
            <el-form :inline="true">
                <el-form-item label="设备名称">
                    <el-input placeholder="请输入设备名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"><i class="iconfont icon-jian"></i>查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitApply"><i class="iconfont icon-tijiaoshenqing"></i>提交申请</el-button>
                </el-form-item>
            </el-form>
            <br>
            <el-table stripe :data="tableData" style="width: 100%" :current-row-key="tableData.id">
                <el-table-column
                    type="index"
                    width="50">
                </el-table-column>
                <el-table-column label="名称">
                    <template slot-scope="slotProps">
                        {{slotProps.row.name}}
                    </template>
                </el-table-column>
                <el-table-column label="型号">
                    <template slot-scope="slotProps">
                        {{slotProps.row.model}}
                    </template>
                </el-table-column>
                <el-table-column label="上线时间">
                    <template slot-scope="slotProps">
                        {{slotProps.row.createTime}}
                    </template>
                </el-table-column>
                <el-table-column label="价格">
                    <template slot-scope="slotProps">
                        {{`${slotProps.row.price}元`}}
                    </template>
                </el-table-column>
                <el-table-column label="数量">
                    <template slot-scope="slotProps">
                        {{slotProps.row.count}}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="slotProps">
                        <div v-if="slotProps.row.isChoose">
                            <el-button type="warning" @click="add(slotProps.$index)"><i class="iconfont icon-yichugouwuche"></i>移除</el-button>
                        </div>
                        <div v-else>
                            <el-button plain @click="add(slotProps.$index)"><i class="iconfont icon-icon-test"></i>添加</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <br>
            <!-- 翻页器 -->
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next, jumper"
                    :pager-count="5"
                    :total="page.total"
                    :page-size="page.pageSize"
                    :current-page="page.currentPage"
                    @current-change="handleCurrentChange"
                >
                </el-pagination>
            </div>
        </el-card>
        <!-- 点击提交申请后出现的弹框 -->
        <div>
            <el-dialog :title="dialog.title" :visible.sync="dialog.show" width="800px" center>
                <el-form ref="submitData" :rules="ruleForm" :model="submitData" label-width="80px">
                    <el-form-item label="借用时间" prop="times">
                        <el-date-picker
                            v-model="submitData.times"
                            type="datetimerange"
                            align="right"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            @change="handlePickerChange"
                            :default-time="['12:00:00', '08:00:00']"
                        >
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="用途" prop="purpose">
                        <el-input v-model="submitData.purpose" placeholder="请输入用途"></el-input>
                    </el-form-item>
                    <el-form-item label="已选设备">
                        <el-table :data="deviceChoose.list" style="width: 100%" :current-row-key="deviceChoose.list.id">
                            <el-table-column label="借用数量" width="174px">
                                <template slot-scope="slotProps">
                                    <el-input-number
                                        size="small"
                                        v-model="slotProps.row.needCount"
                                        :min="1"
                                        :precision="0"
                                        :max="slotProps.row.count"
                                        controls-position="right"
                                    >
                                    1
                                    </el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="名称" width="173px">
                                <template slot-scope="slotProps">
                                    {{slotProps.row.name}}
                                </template>
                            </el-table-column>
                            <el-table-column label="型号" width="173px">
                                <template slot-scope="slotProps">
                                    {{slotProps.row.model}}
                                </template>
                            </el-table-column>
                            <el-table-column label="价格" width="80px">
                                <template slot-scope="slotProps">
                                    {{slotProps.row.price}}
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" width="70px">
                                <template slot-scope="slotProps">
                                    {{slotProps.row.count}}
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitApplyNow('submitData')"><i class="iconfont icon-tijiao"></i>立即提交</el-button>
                        <el-button @click="resetForm('submitData')">重 置</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      tableData: [], // 表格中的数据
      page: {
        total: 10,
        pageSize: 1000,
        currentPage: 1
      },
      deviceChoose: {
        list: [], // 弹出框表格中渲染的数据
        time: '',
        purpose: ''
      },
      dialog: {
        show: false,
        title: '申请设备'
      },
      submitData: { // 点击立即提交时，提交的数据，因为原数据不方便提交
        devices: [],
        startTime: '',
        endTime: '',
        purpose: '',
        id: '',
        times: ''
      },
      ruleForm: { // 表单验证规则，验证不能为空
        times: [
          { required: true, message: '请输入时间', trigger: 'blur' }
        ],
        purpose: [
          { required: true, message: '请输入用途', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 翻页器
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    },
    // 获取列表
    getList() {
      request.get('/items/device/allowMe', { params: {
        size: this.page.pageSize,
        current: this.page.currentPage
      }}).then(res => {
        this.tableData = res.content.records
        this.page.total = res.content.total
      })
    },
    // 选中设备，根据第二个参数判断是添加还是移除
    add(index) {
      var listIndex = this.deviceChoose.list.indexOf(this.tableData[index]) // 判断
      if (listIndex < 0) { // 添加
        if (this.tableData[index].count <= 0) {
          this.$message.warning(`剩余${this.tableData[index].count}件，无法借用`)
        } else {
          this.$set(this.tableData[index], 'isChoose', true) // vue不允许在已创建的实例上动态添加新的根级响应式属性，只能使用Vue.set(object,key,value)方法将响应属性添加到嵌套的对象上
          this.deviceChoose.list.push({ ...this.tableData[index] }) // 将添加的数据存到一个数组里面，使用深拷贝
        }
      } else { // 移除
        this.$set(this.tableData[index], 'isChoose', false)
        this.deviceChoose.list.splice(listIndex, 1)
      }
    },
    // 点击提交申请
    submitApply() {
      if (this.deviceChoose.list.length <= 0) {
        this.$message.warning('请至少选择一种设备')
      } else {
        this.dialog.show = true
      }
    },
    // 点击立即提交
    submitApplyNow(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.deviceChoose.list.length; i++) {
            var { id: deviceId, needCount: count } = { ...this.deviceChoose.list[i] } // 此处解构，获得正确的数据类型，传递给后台
            if (!count) { // 表格中的输入框内的值最小为1，最大为设备数量，但初始时可能为空值，故需要此处的判断（算是遗留问题），弥补表单验证
              this.$message.warning('请将表单填写完整')
              return false
            } else {
              this.submitData.devices.push({ deviceId, count })
            }
          }
          request.post('/items/deviceApply', {
            ...this.submitData
          }).then(res => {
            if (res.code === 0) {
              this.dialog.show = false
            } else {
              this.$message.error(res.content)
            }
          })
        }
      })
    },
    // 点击重置
    resetForm(formName) { // 重置三要素！！     重置，并不是简单地将文本框置空
      this.$refs[formName].resetFields() // 调用对象内的方法
      this.submitData.times = '' // 将数组强制转换为字符串，原数据绑定的数据类型与实际类型不一致（String、Array）
      for (let i = 0; i < this.deviceChoose.list.length; i++) {
        this.deviceChoose.list[i].needCount = 1
      }
    },
    // 时间选择器的change函数
    handlePickerChange(val) {
      this.submitData.startTime = this.transformTime(val[0])
      this.submitData.endTime = this.transformTime(val[1])
      this.submitData.times = val // 数组
    },
    // 转换时间格式
    transformTime(timeData) { // 将标准格式转换成yyyy-mm-dd
      var d = new Date(timeData)
      var datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
      return datetime
    }
  }
}
</script>

<style scoped>
.pagination {
  float: right;
  margin-bottom: 15px;
}
</style>
